<script lang="ts" setup>
import { reactive, ref, unref } from "vue";
import { ArrowDown, Check, Close } from "@element-plus/icons-vue";
import { runStorage, serverStorage } from "@/storage";
import { generateUUID } from "@/utils";
import {
  DropdownInstance,
  ElMessage,
  FormInstance,
  FormRules,
} from "element-plus";

const dropdownRef = ref<DropdownInstance>();
const dialogVisible = ref(false);
const formRef = ref<FormInstance>();

const form = reactive<RunType>({
  id: "",
  tag: "",
  host: "",
  title: "",
  source: "",
  filename: "",
  running: false,
  time: 0,
});
const rules = reactive<FormRules<RunType>>({
  filename: [{ required: true, message: "主程序名称必填", trigger: "blur" }],
  source: [{ required: true, message: "运行发布路径必填", trigger: "blur" }],
});

const open = (row?: RunType) => {
  if (row) {
    form.id = row.id;
    form.tag = row.tag;
    form.title = row.title;
    form.host = row.host;
    form.source = row.source;
    form.running = false;
    form.compression = false;
    form.loading = false;
    form.port = row.port || 5555;
    form.filename = row.filename;
    form.staticPath = row.staticPath || "wwwroot";
  } else {
    form.id = "";
    form.title = "";
    form.host = "http://localhost:8201/swagger";
    form.source = "";
    form.running = false;
    form.filename = "";
    form.staticPath = "wwwroot";
    form.port = 5555;
  }
  dialogVisible.value = true;
};

const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (valid) {
      if (form.id) {
        if (!form.title) form.title = form.filename;
        const item = unref(runStorage).find((item) => item.id === form.id);
        if (item) {
          const editForm: RunType = JSON.parse(JSON.stringify(form));
          // @ts-ignore
          for (const k in form) item[k] = editForm[k];
          ElMessage.success("编辑成功");
        }
      } else {
        if (!form.title) form.title = form.filename;
        form.id = generateUUID();
        runStorage.value.push(JSON.parse(JSON.stringify(form)));
        ElMessage.success("新增成功");
      }
      dialogVisible.value = false;
    } else {
      console.log("error submit!", fields);
    }
  });
};

/**
 * 赋值
 * @param isId 是否赋值id
 * @param row
 */
const onEval = (row: RunType) => {
  if (row) {
    form.title = row.title;
    form.source = row.source;
    form.filename = row.filename;
  } else {
    form.id = "";
    form.title = "";
  }
};

const onCommand = (data: RunType) => {
  onEval(data);
  ElMessage.success("填入成功");
  dropdownRef.value?.handleClose();
};

defineExpose({ open });
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="form.id ? form.title : '本地运行端新增'"
    style="max-width: 1000px"
    width="90%"
    top="10px"
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
      <el-form-item
        label="快捷新增（从已录入的数据代入）"
        v-if="serverStorage.length"
      >
        <el-dropdown ref="dropdownRef" trigger="click" placement="bottom-start">
          <el-button type="primary">
            从已录入的Server-新增
            <el-icon class="ml5">
              <ArrowDown />
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-tree
              :data="serverStorage"
              node-key="id"
              default-expand-all
              :props="{ label: 'title' }"
              style="height: 250px"
              placeholder="请选择一个配置复制"
              class="pa10"
              @node-click="onCommand"
            >
              <template #default="{ data }">
                <span>{{ data.title }}</span>
                <span v-if="data.filename">（{{ data.filename }}）</span>
              </template>
            </el-tree>
          </template>
        </el-dropdown>
      </el-form-item>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="form.title"
              autocomplete="off"
              placeholder="请输入标题"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="标签（可选：如果数据过多，用于标签分类）"
            prop="tag"
          >
            <el-input
              v-model="form.tag"
              autocomplete="off"
              placeholder="请输入标签"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item
        label="本地.NET发布路径（例：D:\projects\CRM\svrtest\Api.Crm.Activity\bin\Release\net5.0\publish）"
        prop="source"
      >
        <el-input
          v-model="form.source"
          autocomplete="off"
          placeholder="请输入本地.NET发布路径"
          clearable
        />
      </el-form-item>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item
            label=".NET主包文件名（例：api_base，必填，否则无法找到主程序无法运行）"
            prop="filename"
          >
            <el-input
              v-model="form.filename"
              autocomplete="off"
              placeholder="请输入文件名"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="API地址（例：http://localhost:8201/swagger）"
            prop="host"
          >
            <div class="flex align-cneter flex-grow-1">
              <el-input
                v-model="form.host"
                autocomplete="off"
                placeholder="请输入API地址"
                clearable
                class="flex-grow-1"
              />
              <el-button
                @click="form.host = 'http://localhost:8201/swagger'"
                class="ml10"
              >
                填入默认
              </el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item
            :label="`静态文件路径（例：发布路劲拼接${form.staticPath}）`"
            prop="staticPath"
          >
            <el-input
              v-model="form.staticPath"
              autocomplete="off"
              placeholder="请输入静态文件路径"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="静态文件服务器的端口（默认：5555）" prop="port">
            <el-input-number
              v-model="form.port"
              autocomplete="off"
              placeholder="请输入端口"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false" :icon="Close">取消</el-button>
        <el-button type="primary" @click="onSubmitForm" :icon="Check">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
